// 创建备忘录
// https://ui.toast.com/tui-editor/
import React, { useState, useEffect, useCallback } from 'react'
import './create-memorandum.scss'
import Editor from '@toast-ui/editor'
import { Input, Button, message } from 'antd'
import { match, RouteComponentProps } from 'react-router-dom'
import {
  serviceCreateMemorandum,
  serviceGetMemorandumById,
  serviceUpdateMemorandum,
} from '../../../request/memorandum'
const defaultTitle = '无标题'

type Props = {
  computedMatch: match<any>
} & RouteComponentProps

let editor: Editor

const CreateMemorandum: React.FC<Props> = function ({
  history,
  computedMatch,
}: Props) {
  const [title, setTitle] = useState(defaultTitle)
  const [loading, setLoading] = useState(false)

  const init = useCallback(() => {
    const id = computedMatch.params.id
    editor = new Editor({
      el: document.querySelector('#edit-section') as HTMLElement,
      initialEditType: 'markdown',
      previewStyle: 'vertical',
      usageStatistics: false,
    })
    editor.getHtml()
    if (id) {
      serviceGetMemorandumById(id).then(res => {
        if (res.data.success) {
          setTitle(res.data.data.title)
          editor.setMarkdown(res.data.data.markdown)
        }
      })
    }
  }, [computedMatch])

  const handleActionButton = useCallback(
    (type: 0 | 1) => {
      if (type === 0) {
        history.replace('/home/memorandum')
        return
      }
      const id = computedMatch.params.id
      if (loading) return
      // 创建或更新
      const params = {
        markdown: editor.getMarkdown(),
        title,
      }
      if (!params.markdown) {
        message.warn('实体内容不能为空')
        return
      }
      setLoading(true)
      ;(id
        ? serviceUpdateMemorandum(id, params)
        : serviceCreateMemorandum(params)
      ).then(res => {
        if (res.data.success) history.replace('/home/memorandum')
      })
    },
    [history, computedMatch, title, loading],
  )
  useEffect(() => {
    init()
    return () => {
      // 销毁实例
      editor?.remove()
    }
  }, [init])

  return (
    <div className="editor-page">
      <Input
        className="input-title"
        placeholder={defaultTitle}
        maxLength={50}
        size="large"
        value={title}
        onChange={e => setTitle(e.target.value)}
        onBlur={() => !title && setTitle(defaultTitle)}
      ></Input>
      <div id="edit-section"></div>
      <div className="button-group">
        <Button onClick={handleActionButton.bind(null, 0)}>取消</Button>
        <Button
          type="primary"
          onClick={handleActionButton.bind(null, 1)}
          loading={loading}
        >
          提交
        </Button>
      </div>
    </div>
  )
}

export default CreateMemorandum
